<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #toolbar>
        <Dropdown placement="bottom">
          <Button type="primary" class="mr-2">添加规则链</Button>
          <template #overlay>
            <Menu @click="addRuleClick">
              <MenuItem key="newRule">
                <Icon icon="material-symbols:file-copy-sharp" /> 创建新的规则链</MenuItem
              >
            </Menu>
          </template>
        </Dropdown>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:edit-filled',
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:eye-filled',
                tooltip: {
                  title: '详情',
                  placement: 'top',
                },
                onClick: handleMore.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                disabled: record.root,
                onClick: handleDelete.bind(null, record),
              },
            ]"
            :drop-down-actions="[
              {
                icon: 'material-symbols:download-2',
                label: '导出规则链',
                onClick: handleDownload.bind(null, record),
              },
              {
                icon: 'ic:sharp-flag',
                label: '设置为根规则链',
                disabled: record.root,
                onClick: handleFlag.bind(null, record),
              },
              {
                icon: ICON.EDIT,
                label: '绘制规则链',
                onClick: handleEditRule.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <PublicDrawer
      :show-tabs="[
        'detail',
        'attribute',
        'telemetry',
        'alarm',
        'event',
        'association',
        'auditLogs',
        'version',
      ]"
      @register="registerDrawer"
      @update-desc-data="handleUpdateDescData"
    />
    <AddRule @register="registerModal" @close-add-rule-falg="closeAddRuleFalg" />
  </div>
</template>

<script lang="ts" setup>
  import { ICON } from '/@/enums/iconEnum';
  import { Alert, Tooltip } from 'ant-design-vue';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import { Dropdown, Button, Menu, MenuItem } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { ruleColumns, searchFormSchema, detailSchema } from './components/rule.data';
  import Icon from '/@/components/Icon';
  import {
    getRuleChainsList,
    deleteTheRule,
    falgTheRule,
    getTheRuleInfo,
    downloadTheRule,
    getEdgeList,
  } from '/@/api/thingsborad/rule/rule';
  import { ruleParams } from '/@/api/thingsborad/rule/model/ruleModel';
  import { onMounted, ref } from 'vue';
  import AddRule from './components/AddRule.vue';
  import { useModal } from '/@/components/Modal';
  import dayjs from 'dayjs';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDrawer } from '/@/components/Drawer';
  import { useRoute } from 'vue-router';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { router } from '/@/router';
  const { createConfirm } = useMessage();
  const checkedKeys = ref<any>([]);
  let params = ref<ruleParams>({
    pageSize: 10,
    page: 0,
    sortProperty: 'createdTime',
    sortOrder: 'DESC',
    type: 'CORE',
  });
  let ruleTableData = ref<Array<any>>([]);
  const route = useRoute();
  onMounted(() => {
    // 初始化表格数据
    if (route.params.id === undefined) {
      setProps({
        api: getRuleChainsList,
        beforeFetch: (val) => {
          params.value.page = val.page - 1;
          params.value.pageSize = val.pageSize;
          params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
          params.value.sortProperty = 'createdTime';

          if (val.deptName === null) {
            params.value.textSearch = undefined;
          } else {
            params.value.textSearch = val.deptName;
          }
          return params.value;
        },
        afterFetch: (res) => {
          ruleTableData.value = [];
          if (res.length === 0) {
            return ruleTableData.value;
          }
          res.forEach((item) => {
            ruleTableData.value.push({
              createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
              name: item.name,
              root: item.root,
              id: item.id.id,
              info: item,
            });
          });
          return ruleTableData.value;
        },
        fetchSetting: {
          pageField: 'page',
          sizeField: 'pageSize',
          listField: 'data',
          totalField: 'totalElements',
        },
      });
    } else {
      setProps({
        api: getEdgeList,
        beforeFetch: (val) => {
          params.value.page = val.page - 1;
          params.value.pageSize = val.pageSize;
          params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
          params.value.sortProperty = 'createdTime';

          if (val.deptName === null) {
            params.value.textSearch = undefined;
          } else {
            params.value.textSearch = val.deptName;
          }
          let data: any = {
            id: route.params.id,
            params: params.value,
          };
          return data;
        },
        afterFetch: (res) => {
          ruleTableData.value = [];
          if (res.length === 0) {
            return ruleTableData.value;
          }
          res.forEach((item) => {
            ruleTableData.value.push({
              createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
              name: item.name,
              root: item.root,
              id: item.id.id,
              info: item,
            });
          });
          return ruleTableData.value;
        },
        fetchSetting: {
          pageField: 'page',
          sizeField: 'pageSize',
          listField: 'data',
          totalField: 'totalElements',
        },
      });
    }
  });
  const [registerDrawer, { openDrawer }] = useDrawer();

  const [registerModal, { openModal, setModalProps }] = useModal();
  //表格初始化
  const [registerTable, { reload, setProps }] = useTable({
    title: '规则链库',
    columns: ruleColumns,
    ...tableStyleSetting,
    formConfig: {
      layout: 'horizontal',
      schemas: searchFormSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 8 },
        lg: { span: 6, offset: 12 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
      getCheckboxProps: (record) => ({
        disabled: record.root,
      }),
    },
  });
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除  '${checkedKeys.value.length}' 个规则链吗？`,
      content: '请注意：确认后，规则链及其所有相关数据将不可恢复。',
      onOk: async () => {
        for (const item of checkedKeys.value) {
          await deleteTheRule(item);
        }
        reload();
        //初始化 表格数据
        checkedKeys.value = [];
      },
    });
  };

  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 抽屉详情数据更改
  const handleUpdateDescData = (value) => {
    value.assetName = value.name;
    value.assetConfiguration = value.assetProfileName;
    value.label = value.label;
    value.customer = value.customerTitle;
    value.isOpen = value.customerIsPublic;
  };
  function handleMore(record: Recordable) {
    openDrawer(true, {
      entityType: ENTITY_TYPE.RULE_CHAIN,
      entityId: record.id,
      title: record.name,
      api: getTheRuleInfo,
      detailSchema: detailSchema,
      params: record.id,
    });
  }

  function handleEdit(record: Recordable) {
    setModalProps({
      title: '编辑规则链',
      okText: '保存',
    });
    openModal(true, record);
  }
  async function handleDownload(record: Recordable) {
    try {
      const theResourceFileData = await downloadTheRule(record.id);
      const theResourceFileDataMetadata = await downloadTheRule(record.id + '/metadata');

      let downloadJson: any = {
        ruleChain: {
          additionalInfo: theResourceFileData.additionalInfo,
          name: theResourceFileData.name,
          type: 'EDGE',
          firstRuleNodeId: theResourceFileData.firstRuleNodeId,
          root: theResourceFileData.root,
          debugMode: theResourceFileData.debugMode,
          configuration: theResourceFileData.configuration,
          externalId: theResourceFileData.externalId,
        },
        metadata: {
          firstNodeIndex: theResourceFileDataMetadata.firstNodeIndex,
          nodes: theResourceFileDataMetadata.nodes,
          connections: theResourceFileDataMetadata.connections,
          ruleChainConnections: theResourceFileDataMetadata.ruleChainConnections,
        },
      };
      const blob = new Blob([JSON.stringify(downloadJson)], { type: 'text/plain' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = record.name + '.json'; // 设置下载后的文件名
      document.body.appendChild(link); // 需要添加到DOM中才能触发点击事件
      link.click();
      document.body.removeChild(link); // 下载后移除元素
      window.URL.revokeObjectURL(url); // 释放内存
    } catch (error) {}
  }
  async function handleFlag(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要设置  ${record.name}  为根规则链吗？`,
      content: '确认后，规则链将变为根规格链，并将处理所有传入的传输消息。',
      onOk: async () => {
        await falgTheRule(record.info);
        reload();
      },
    });
  }
  async function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要删除  ${record.name}  吗？`,
      content: '请注意，确认后，规则链和所有相关数据将不可恢复。',
      onOk: async () => {
        await deleteTheRule(record.id);
        reload();
      },
    });
  }
  // 添加规则链点击事件
  function addRuleClick(value) {
    if (value.key === 'newRule') {
      setModalProps({
        title: '添加规则链',
        okText: '保存',
      });
      openModal(true, true);
    }
  }
  // 组件通信 addrule 弹窗关闭
  function closeAddRuleFalg() {
    // 初始化表格数据
    reload();
  }
  // 绘制规则链页面
  const handleEditRule = (record: Recordable) => {
    // go({
    //   name: 'EditRuleChain',
    //   params: record.id,
    // });

    router.push({ path: `/tb-rule/TbrulePage/rule-chain/${record.id}` });
  };
</script>
